/* eslint-disable */
import { maintenanceHttp } from '/@/utils/http/axios';
import {
  ActionParams,
  CceAlertRuleItem,
  CceAlertRuleParams,
  CceDimensionParams,
  CceDimensionsKV,
  CceDimensionValueParams,
  CceMetricNameItem,
  CceRecordItem,
  CceRecordParams,
  CceRuleItem,
  CesCreateRuleParams,
  CesDetail,
  CesDetailParams,
  CesEditRuleParams,
  CesRecordDetailItem,
  CesRecordDetailParams,
  CesRecordParams,
  CesRecordResult,
  CesRuleItem,
  CesRuleParams,
  CesRuleResult,
  DeleteCceParams,
  DeleteCesParams,
  DetailRuleParams,
  dimensionItem,
  dimensionParams,
  EventListParams,
  MetricsListParams,
  NamespaceItem,
  resourceItem,
  ResourceListParams,
  EventQueryParams,
  EventListResultModel,
  EventDetailQueryParams,
  EventDetailListResultModel,
  EventUserQueryParams,
  EventUserListResultModel,
  EventSourceQueryParams,
  EventSourceListResultModel,
  EventCustomParams,
} from '/@/api/maintenance-center/alarm/model/alarmModel';
import { toRaw } from 'vue';
import moment from 'moment';
import { stampToDate } from '/@/utils/dateUtil';

enum Api {
  GET_CES_RULE_LIST = '/v1/maintenance/alarm/cesAlarmRules',
  GET_CES_RECORD_LIST = '/v1/maintenance/alarm/cesAlarmHistories',
  GET_CCE_RULE_LIST = '/v1/maintenance/alarm/aom/ruleList',
  GET_CCE_RECORD_LIST = '/v1/maintenance/alarm/aom/list',
  GET_CCE_STATISTIC = '/v1/maintenance/alarm/aom/statistic',
  GET_CES_NAMESPACE = '/v1/maintenance/alarm/form/namespace',
  GET_CES_EVENT = '/v1/maintenance/alarm/form/events',
  GET_CES_DIMENSION = '/v1/maintenance/alarm/form/dimension',
  GET_CES_RESOURCE = '/v1/maintenance/alarm/form/resourceList',
  GET_CES_METRICS = '/v1/maintenance/alarm/form/metrics',
  ACTION_CES_ALARM_RULE = '/v1/maintenance/alarm/actionCesAlarmRule',
  DELETE_CES_ALARM_RULE = '/v1/maintenance/alarm/deleteCesAlarmRule',
  CREATE_CES_ALARM_RULE = '/v1/maintenance/alarm/createCesAlarmRule',
  VIEW_CES_ALARM_RULE_DETAIL = '/v1/maintenance/alarm/cesAlarmRuleDetail',
  UPDATE_CES_ALARM_RULE = '/v1/maintenance/alarm/updateCesAlarmRule',
  GET_CCE_METRICS_NAME = '/v1/maintenance/alarm/aom/metrics',
  GET_CCE_DIMENSION = '/v1/maintenance/alarm/aom/dimensionKey',
  GET_CCE_DIMENSION_VALUE = '/v1/maintenance/alarm/aom/dimensionValue',
  CREATE_CCE_ALERT_RULE = '/v1/maintenance/alarm/aom/createAlertRule',
  DELETE_CCE_ALERT_RULE = '/v1/maintenance/alarm/aom/removeAlertRule',
  GET_CCE_ALERT_RULE_DETAIL = '/v1/maintenance/alarm/aom/alertRuleDetails',
  UPDATE_CCE_ALERT_RULE = '/v1/maintenance/alarm/aom/editAlertRule',
  GET_CES_ALERT_RULE_DETAIL = '/v1/maintenance/alarm/cesAlarmHistoryDetail',
  GET_EVENT_LIST = '/v1/maintenance/alarm/eventList',
  GET_EVENT_DETAIL_LIST = '/v1/maintenance/alarm/eventDetails',
  GET_EVENT_USER_LIST = '/v1/maintenance/alarm/eventSources',
  GET_EVENT_SOURCE_LIST = '/v1/maintenance/alarm/eventSources',
  GET_CES_CUSTOM_EVENT = '/v1/maintenance/alarm/eventList',
}

export const getCesRuleList = async (params: CesRuleParams) => {
  const result: CesRuleItem[] = await maintenanceHttp.get<CesRuleResult>({
    url: Api.GET_CES_RULE_LIST,
    params,
  });
  result.items.forEach((item) => {
    if (item.status === true) {
      item.status = '已启用';
      item.button = '停用';
    } else if (item.status === false) {
      item.status = '已停用';
      item.button = '启用';
    }
  });
  return result;
};

export const getCceRuleList = async () => {
  const result: CceRuleItem[] = await maintenanceHttp.get<CceRuleItem[]>({
    url: Api.GET_CCE_RULE_LIST,
  });
  result.forEach((item) => {
    item.threshold = item.comparisonOperator + '\t' + item.threshold;
    switch (item.namespace) {
      case 'PAAS.AGGR':
        item.namespace = '集群';
        break;
      case 'PAAS.NODE':
        item.namespace = '主机';
        break;
      case 'PAAS.CONTAINER':
        item.namespace = '组件';
        break;
    }
  });
  return result;
};
export const getCesRecordList = async (params: CesRecordParams) => {
  const result = await maintenanceHttp.get<CesRecordResult>({
    url: Api.GET_CES_RECORD_LIST,
    params,
  });
  result.items.forEach((item) => {
    switch (item.level) {
      case 1:
        item.level = '紧急';
        break;
      case 2:
        item.level = '重要';
        break;
      case 3:
        item.level = '次要';
        break;
      case 4:
        item.level = '提示';
        break;
    }
    switch (item.status) {
      case 'alarm':
        item.status = '告警';
        break;
      case 'ok':
        item.status = '正常';
        break;
      case 'invalid':
        item.status = '已失效';
        break;
    }
  });
  return result;
};

export const getCesRecordDetail = (params: CesRecordDetailParams) => {
  return maintenanceHttp.get<CesRecordDetailItem>({
    url: Api.GET_CES_ALERT_RULE_DETAIL,
    params,
  });
};

export const getNamespace = () => {
  return maintenanceHttp.get<NamespaceItem[]>({
    url: Api.GET_CES_NAMESPACE,
  });
};

export const getDimension = (params: dimensionParams) => {
  return maintenanceHttp.get<dimensionItem[]>({
    url: Api.GET_CES_DIMENSION,
    params,
  });
};

export const getResourceList = (params: ResourceListParams) => {
  return maintenanceHttp.get<resourceItem[]>({
    url: Api.GET_CES_RESOURCE,
    params,
  });
};
export const getEventList = (params: EventListParams) => {
  return maintenanceHttp.get<dimensionItem[]>({
    url: Api.GET_CES_EVENT,
    params,
  });
};

export const getCustomEventList = (params: EventCustomParams) => {
  const result = maintenanceHttp.post<dimensionItem[]>({
    url: Api.GET_CES_CUSTOM_EVENT,
    params,
  });
  return result.records;
};

export const getCesMetricsList = async (params: MetricsListParams) => {
  const result = await maintenanceHttp.get<resourceItem[]>({
    url: Api.GET_CES_METRICS,
    params,
  });
  result.forEach((item) => {
    item.metricId = item.metricId + '-' + item.unit;
  });
  return result;
};

export const getCceRecordList = (params: CceRecordParams) => {
  params.sort = {};
  params.metadataRelation = [];
  params.sort.orderBy = [];
  params.sort.orderBy.push(toRaw(params.orderBy));
  params.sort.order = toRaw(params.order);
  params.limit = toRaw(params.limit);
  params.eventSeverity = [];
  params.eventType = [];
  params.resourceType = [];
  if (params.timeRange1 instanceof Array) {
    const time = (params.timeRange1[1] - params.timeRange1[0]) / 60000;
    params.timeRange = params.timeRange1[0] + '.' + params.timeRange1[1] + '.' + time;
  } else {
    params.timeRange = params.timeRange1;
  }
  params.limit?.forEach((item) => {
    switch (item) {
      case 'Critical':
        params.eventSeverity.push(item);
        break;
      case 'Major':
        params.eventSeverity.push(item);
        break;
      case 'Minor':
        params.eventSeverity.push(item);
        break;
      case 'Info':
        params.eventSeverity.push(item);
        break;
      case 'alarm':
        params.eventType.push(item);
        break;
      case 'service':
        params.resourceType.push(item);
        break;
    }
  });
  if (params.eventSeverity.length !== 0) {
    const es = {};
    es.key = 'event_severity';
    es.relation = 'AND';
    es.value = params.eventSeverity;
    params.metadataRelation.push(es);
  }

  if (params.eventType.length !== 0) {
    const es = {};
    es.key = 'event_type';
    es.relation = 'AND';
    es.value = params.eventType;
    params.metadataRelation.push(es);
  }

  if (params.resourceType.length !== 0) {
    const es = {};
    es.key = 'resource_type';
    es.relation = 'AND';
    es.value = params.resourceType;
    params.metadataRelation.push(es);
  }
  return maintenanceHttp.post<CceRecordItem[]>({
    url: Api.GET_CCE_RECORD_LIST,
    params,
  });
};

export const getMetricName = async () => {
  const result: CceMetricNameItem[] = await maintenanceHttp.get<CceMetricNameItem[]>({
    url: Api.GET_CCE_METRICS_NAME,
  });
  let namespaceCount = 0;
  let childrenCount = 0;

  result.forEach((item) => {
    item.title = item.namespace;
    item.key = '0-' + namespaceCount;
    item.value = item.namespace;
    item.children.forEach((i) => {
      i.title = i.metricNameZh;
      i.value = item.namespace + '-' + i.metricName;
      i.key = '0-' + namespaceCount + '-' + childrenCount;
      childrenCount++;
    });
    namespaceCount++;
  });
  return result;
};

export const getCCEDimensionKey = async (params: CceDimensionParams) => {
  const namespaceItem = params.namespace.split('-');
  params.namespace = namespaceItem[0];
  params.metricName = namespaceItem[1];
  return await maintenanceHttp.get<CceDimensionsKV[]>({
    url: Api.GET_CCE_DIMENSION,
    params,
  });
};

export const getCCEDimensionValue = async (params: CceDimensionValueParams) => {
  const namespaceItem = params.namespace.split('-');
  params.namespace = namespaceItem[0];
  params.metricName = namespaceItem[1];
  params.key = params.dimensionsKey;
  return await maintenanceHttp.get<CceDimensionsKV[]>({
    url: Api.GET_CCE_DIMENSION_VALUE,
    params,
  });
};

export const createAlertRule = (params: CceAlertRuleParams) => {
  params.namespace = params.metricName.split('-')[0];
  params.metricName = params.metricName.split('-')[1];
  return maintenanceHttp.post<string>({
    url: Api.CREATE_CCE_ALERT_RULE,
    params,
  });
};

export const actionCesAlarmRule = (params: ActionParams) => {
  return maintenanceHttp.put<boolean>({
    url: Api.ACTION_CES_ALARM_RULE + '?alarmId=' + params.alarmId + '&status=' + params.status,
  });
};

export const deleteCesAlarmRule = (params: DeleteCesParams) => {
  return maintenanceHttp.delete<string>({
    url: Api.DELETE_CES_ALARM_RULE + '?alarmId=' + params.alarmId,
  });
};

export const deleteCceAlertRule = (params: DeleteCceParams) => {
  return maintenanceHttp.delete<string>({
    url: Api.DELETE_CCE_ALERT_RULE + '?alarmRuleId=' + params.alarmRuleId,
  });
};

export const viewCceRuleDetail = async (params: DetailRuleParams) => {
  const result: CceAlertRuleItem = await maintenanceHttp.get<CceAlertRuleItem>({
    url: Api.GET_CCE_ALERT_RULE_DETAIL,
    params,
  });
  result.alarmLevel = result.alarmLevel.toString();
  result.evaluationPeriods = result.evaluationPeriods.toString();
  result.period = result.period.toString();
  console.log(result);
  return result;
};

export const updateCesRule = (params: CesEditRuleParams) => {
  return maintenanceHttp.post<string>({
    url: Api.UPDATE_CES_ALARM_RULE,
    params,
  });
};

export const viewCesRuleDetail = async (params: CesDetailParams) => {
  const cesRule: CesDetail = await maintenanceHttp.get<CesDetail>({
    url: Api.VIEW_CES_ALARM_RULE_DETAIL,
    params,
  });

  console.log(cesRule);
  if (cesRule.notificationEnabled) {
    cesRule.notificationTrigger = [];
    if (cesRule.alarmTrigger === true) {
      cesRule.notificationTrigger.push('alarmTrigger');
    }
    if (cesRule.okTrigger === true) {
      cesRule.notificationTrigger.push('okTrigger');
    }
    cesRule.notificationBeginTime = cesRule.notificationBeginTime;
    cesRule.notificationEndTime = cesRule.notificationEndTime;
    cesRule.notificationTime = [];
    cesRule.notificationTime.push(moment(cesRule.notificationBeginTime));
    cesRule.notificationTime.push(moment(cesRule.notificationEndTime));
    console.log(cesRule.notificationTime);
    cesRule.tempUrns = [];
    cesRule.smnUrns.forEach((item) => {
      cesRule.tempUrns.push(item.displayName);
    });
    cesRule.smnUrns = {};
    cesRule.smnUrns = cesRule.tempUrns;
  }
  console.log(cesRule);
  return cesRule;
};

export const createCesRule = (params: CesCreateRuleParams) => {
  params.alarmTrigger = false;
  params.okTrigger = false;
  if (params.notificationEnabled === undefined) {
    params.notificationEnabled = false;
  }
  if (params.notificationEnabled === false) {
    params.notificationTrigger = undefined;
    params.notificationTime = undefined;
    params.notificationBeginTime = undefined;
    params.notificationEndTime = undefined;
  }
  params.enabled = true;
  if (params.notificationTrigger != undefined) {
    params.notificationTrigger.forEach((item) => {
      switch (item) {
        case 'okTrigger':
          params.okTrigger = true;
          break;
        case 'alarmTrigger':
          params.alarmTrigger = true;
          break;
      }
    });
  }
  if (params.notificationTime !== undefined) {
    params.notificationBeginTime = moment(params.notificationTime[0].$d.valueOf()).format('HH:mm');
    params.notificationEndTime = moment(params.notificationTime[1].$d.valueOf()).format('HH:mm');
  }
  return maintenanceHttp.post<string>({
    url: Api.CREATE_CES_ALARM_RULE,
    params,
  });
};

export const editAlertRule = (params: CceAlertRuleParams) => {
  return maintenanceHttp.post<string>({
    url: Api.UPDATE_CCE_ALERT_RULE,
    params,
  });
};

export const getEventListByPage = async (params: EventQueryParams) => {
  let res = await maintenanceHttp.post<EventListResultModel>({
    url: Api.GET_EVENT_LIST,
    params,
  });
  res.items.map((item) => {
    item.latestOccurTimeStr = stampToDate(item.latestOccurTime);
    return item;
  });
  return res;
};

export const getEventDetailListByPage = async (params: EventDetailQueryParams) => {
  const result = await maintenanceHttp.post<EventDetailListResultModel>({
    url: Api.GET_EVENT_DETAIL_LIST,
    params,
  });
  result.items.map((item) => {
    item.timeStr = stampToDate(item.time);
    return item;
  });
  return result.items;
};

export const getEventUserList = async (params: EventUserQueryParams) => {
  const result = await maintenanceHttp.get<EventUserListResultModel[]>({
    url: Api.GET_EVENT_USER_LIST,
    params,
  });
  return result.map((item) => {
    return {
      label: item,
      value: item,
    };
  });
};

export const getEventSourceList = async (params: EventSourceQueryParams) => {
  const result = await maintenanceHttp.get<EventSourceListResultModel[]>({
    url: Api.GET_EVENT_SOURCE_LIST,
    params,
  });
  return result.map((item) => {
    return {
      label: item,
      value: item,
    };
  });
};
